/**
 * customer 模块数据层
 * @author 710335997@qq.com
 * @time 2016年3月21日20:02:49
 */
var _ljs=require("../mmlog").root("[sever/db/customer.js]");
var db = require("./db");

module.exports = {
	/**
	 * 通过渠道账号查询用户ID
	 * @param {Object} param [渠道,账号]
	 * @param {Object} callback
	 */
	selectIdByAccount:function(param,callback){
		db.query({
			sql: "SELECT T2.CUSTOMER_UUID cid,T1.NAME name,T1.MOBILE mobile,T1.EMAIL email, T1.ADDRESS address, T1.CREATE_TIME createTime, T3.CREATE_TIME lastTime, T3.SESSION_ID lastSession,count(*) count FROM T_CUSTOMER T1,T_CUSTOMER_ACCOUNT T2,(SELECT * FROM T_SESSION ORDER BY CREATE_TIME DESC) T3 WHERE T1.UUID=T2.CUSTOMER_UUID AND T1.UUID = T3.USER_ID AND T2.CHANNEL=? AND T2.ACCOUNT=?",
			values: param
		}, callback)
	},
	
	/**
	 * 插入新用户ID信息
	 * @param {Object} uuid 随机生成UUID
	 * @param {Object} time 创建时间
	 * @param {Object} callback
	 */
	insertCustomer:function(uuid,time,callback){
		var sql="INSERT INTO `MMLINK`.`T_CUSTOMER` (`UUID`,`CREATE_TIME`, `STATUS`) VALUES (?, ?, 0)";
		db.query({
			sql: sql,
			values: [uuid,time,0]
		}, callback)
	},
	
	/**
	 * 插入用户渠道账号信息
	 * @param {Object} uuid 随机生成UUID 
	 * @param {Object} customerId 用户ID 
	 * @param {Object} channel 渠道号
	 * @param {Object} account 渠道账号
	 * @param {Object} time 创建时间
	 * @param {Object} callback
	 */
	insertCustomerAccoount:function(uuid,customerId,channel,account,time,callback){
		var sql="INSERT INTO `MMLINK`.`T_CUSTOMER_ACCOUNT` (`UUID`, `CUSTOMER_UUID`, `ACCOUNT`, `CHANNEL`, `CREATE_TIME`) VALUES (?, ?, ?, ?, ?)";	
		db.query({
			sql: sql,
			values: [uuid,customerId,account,channel,time]
		}, callback)
	},
	
	updateCustomer:function(cid,obj,callback){
		var sql="UPDATE T_CUSTOMER SET ";
		var tmp=[]
		for(var p in obj){
			if(obj.hasOwnProperty(p)){
				tmp.push(p+"='"+obj[p]+"'");
			}
		}
		sql+=tmp.join(" , ")+" WHERE UUID='"+cid+"'";
		_ljs.debug("更新用户信息:\n",sql);
		db.query({
			sql: sql,
			values: null
		}, callback)
	}


}